import { getImageAdvertiseInfo } from '../advertiseService';
import { swiperAdvertise, getAds } from '../advertiseConfiguration';
import _ from 'lodash-es';

Component({
  data: {
    timer: 0,
    timeout: 0,
    height: 650,
    pictures: [],
    visible: false,
  },
  props: {
    advertiseCode: swiperAdvertise.defaultCode,
    onAdvertiseInit: () => true, // 返回true显示广告，false不显示
    onClose: () => true, // 返回true关闭广告，false不关闭
  },
  didMount() {
    this.getAndShowAdvertise();
  },
  didUpdate(preProps) {
    if (preProps.advertiseCode !== this.props.advertiseCode) {
      this.getAndShowAdvertise();
    }
  },
  didUnMount() {
    const { timer } = this.data;
    clearInterval(timer);
  },
  methods: {
    async getAndShowAdvertise() {
      const { advertiseCode } = this.props;
      const adList = await getAds(advertiseCode);
      if (_.size(adList) === 0) {
        return;
      }
      const showAdvertise = await this.props.onAdvertiseInit();
      if (showAdvertise === false) {
        return;
      }
      try {
        const { pictureGroup, height, timeout } = getImageAdvertiseInfo(adList[0].content);
        const pictures = pictureGroup[0];
        this.setData({ pictures, height, timeout, visible: true }, () => this.setTimer());
      } catch (e) {
        this.props.onClose();
        swiperAdvertise.errorLog(advertiseCode, JSON.stringify(e), 'swiper-advertise.js_mini-app-mobile');
      }
    },
    handleCloseAdvertise() {
      if (this.props.onClose() !== false) {
        this.setData({ visible: false });
      }
    },
    handleImgTap({
      target: {
        dataset: { ele },
      },
    }) {
      if (ele.href) {
        swiperAdvertise.jumpTo({ url: ele.href });
      } else if (ele.chat) {
        swiperAdvertise.chat(ele.nick || '赤兔名品', ele.chat);
      }
    },
    setTimer() {
      const { timeout, timer } = this.data;
      clearInterval(timer);
      if (timeout) {
        const newTimer = setInterval(() => {
          const newTimeout = timeout - 1;
          this.setData({ timeout: newTimeout });
          if (newTimeout <= 0) {
            clearInterval(timer);
          }
        }, 1000);
        this.setData({ timer: newTimer });
      }
    },
  },
});
